package org.easy.core.util;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;


public class BeanCopierUtil extends BeanUtils {

    private BeanCopierUtil() {
    }

    /**
     * 对象拷贝
     *
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> T copy(Object source, T target) {
        BeanUtils.copyProperties(source, target);
        return target;
    }

    /**
     * 对象拷贝
     *
     * @param source
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> T copy(Object source, Class<T> targetClass) {
        T t = null;
        try {
            t = targetClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        //此处不使用转换器,类型不同时跳过,已由IAction.run实现
        BeanUtils.copyProperties(source, t);
        return t;
    }

    /**
     * 列表拷贝
     *
     * @param sources
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList(Object sources, Class<T> targetClass) {
        List<T> list = new ArrayList<>();
        if (sources instanceof List) {
            for (Object source : (List) sources) {
                list.add(copy(source, targetClass));
            }
        }
        return list;
    }


}
